/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database.dao;

import database.common.GenericDao;
import database.entity.Categories;
import database.entity.Medicines;
import java.math.BigDecimal;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Administrator
 */
public class MedicinesDao extends GenericDao<Medicines, Integer> {

    public List<Medicines> getAllAvaiable() {
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        Criteria c = session.createCriteria(Medicines.class);
        c.add(Restrictions.eq("status", 0));
        List<Medicines> list = c.list();
        session.flush();
        session.getTransaction().commit();
        return list;
    }

    public List<Medicines> search(String name, double price, Categories ct, String code) {
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        Criteria c = session.createCriteria(Medicines.class);
        if (!name.isEmpty()) {
            c.add(Restrictions.like("name", "%" + name + "%"));
        }
        if (price > 0) {
            c.add(Restrictions.le("price", BigDecimal.valueOf(price)));
        }
        if (ct != null && !ct.getName().equals("All Categories")) {
            c.add(Restrictions.eq("category", ct));
        }
        if (!code.isEmpty()) {
            c.add(Restrictions.like("code", "%" + code + "%"));
        }
        c.add(Restrictions.eq("status", 0));
        List<Medicines> list = c.list();
        session.flush();
        session.getTransaction().commit();
        return list;
    }

    public boolean contain(String code) {
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        Criteria c = session.createCriteria(Medicines.class);
        c.add(Restrictions.eq("code", code));
        int number = c.list().size();
        session.flush();
        session.getTransaction().commit();
        if (number > 0) {
            return true;
        } else {
            return false;
        }
    }

    public Medicines getByCode(String code) {
        List<Medicines> meds;
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        Criteria c = session.createCriteria(Medicines.class);
        c.add(Restrictions.eq("code", code));
        meds = c.list();
        session.flush();
        session.getTransaction().commit();
        if (meds.size() == 1) {
            return meds.get(0);
        } else {
            return null;
        }
    }
}
